package kt_test.util

import android.content.Context
import kotlinx.coroutines.*
import kt_test.room.database.OxygenDatabase
import kt_test.room.entity.*
import org.json.JSONObject

object JsonOxygenInserter {

    fun insertFromAssets(context: Context, fileName: String) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val json = context.assets.open("oxygen_test/$fileName").bufferedReader().use { it.readText() }
                val jsonObject = JSONObject(json)

                val userId = jsonObject.getString("userId")
                val gender = jsonObject.getString("gender")
                val age = jsonObject.getInt("age")

                val user = UserInfoEntity(userId, gender, age)
                val samples = mutableListOf<OxygenSampleEntity>()

                val array = jsonObject.getJSONArray("samples")
                for (i in 0 until array.length()) {
                    val item = array.getJSONObject(i)
                    samples.add(
                        OxygenSampleEntity(
                            userId = userId,
                            time = item.getString("time"),
                            spo2 = item.getDouble("spo2")
                        )
                    )
                }

                val db = OxygenDatabase.getDatabase(context.applicationContext)
                db.userInfoDao().insert(user)
                db.oxygenSampleDao().insertSamples(samples)

                // 成功日志
                println("JsonOxygenInserter: 成功插入用户 $userId, 样本数量: ${samples.size}")
            } catch (e: Exception) {
                e.printStackTrace()
                println("JsonOxygenInserter: 插入数据异常 ${e.message}")
            }
        }
    }
}
